sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.GRAYSCALE) # 设置像素格式为灰度
sensor.set_framesize(sensor.QVGA) # 设置帧大小为QVGA
sensor.skip_frames(time = 2000) # 等待设置生效

# 设置阈值来识别黑色物体
thresholdB = (0,50) # 较低的阈值可以识别更暗的颜色为黑色
def find_min(blobs):
    min_size=100000
    for blob in blobs:
        if blob.pixels() < min_size and blob.pixels()>7000:
            MIN_blob=blob
            min_size = blob.pixels()
    return MIN_blob
###################################################################################
##白色
thresholdW=(240,255)
def find_max(blobs):
    max_size=0
    for blob in blobs:
        if blob.pixels() > max_size:
            MAX_blob=blob
            max_size = blob.pixels()
    return MAX_blob


while(True):
    img = sensor.snapshot() # 捕捉图像
    blobsB = img.find_blobs([thresholdB]) # 查找黑色物体
    min_blob=find_min(blobsB)
    if min_blob.pixel!=100000:
        img.draw_rectangle(min_blob.rect())
        img.draw_cross(min_blob.cx(), min_blob.cy(), color = (255, 0, 0)) # 在物体中心绘制十字
        # 尝试确定物体是否为矩形
        # 这里我们使用宽高比来简单判断，但可能不够准确
        # 对于更精确的矩形检测，可以使用霍夫变换等方法
        print("Found a black rectangle at position:", (min_blob.cx(), min_blob.cy()))

    ##############################################################
    blobsW=img.find_blobs([thresholdW])#查找白色物体
    max_blob=find_max(blobsW)
    if max_blob.pixels!=0:
        img.draw_rectangle(max_blob.rect())
        img.draw_cross(max_blob.cx(), max_blob.cy(), color = (255, 0, 0)) # 在物体中心绘制十字
        print("Found a black rectangle at position:", (max_blob.cx(), max_blob.cy()))
